/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * RecursPanel.java
 *
 * Created on 14-dic-2011, 19:22:34
 */
package edu.uoc.tdp.pac4.only5.gui.client.panels.manteniment;

import edu.uoc.tdp.pac4.only5.gui.client.panels.AbstractPanel;
import edu.uoc.tdp.pac4.only5.manager.ResourceManager;
import edu.uoc.tdp.pac4.only5.domain.Resource;

import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;

import java.util.Date;
import javax.swing.*;

/**
 *
 * @author Alex
 */
public class RecursPanel extends AbstractPanel {

    private ResourceManager resourceManager;
    
    Resource resource = null;


    /** Creates new form RecursPanel */
    public RecursPanel(ResourceManager resourceManager) {
        super();
        initComponents();
        posicioInicialBotons();
        setLabels();
        this.resourceManager = resourceManager;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lbl_recursos_titol = new javax.swing.JLabel();
        lbl_recurs_codiRecurs = new javax.swing.JLabel();
        txt_recurs_codiRecurs = new javax.swing.JTextField();
        lbl_recurs_descripcio = new javax.swing.JLabel();
        txt_recurs_descripcio = new javax.swing.JTextField();
        lbl_recurs_existencies = new javax.swing.JLabel();
        txt_recurs_existencies = new javax.swing.JTextField();
        lbl_recurs_preuHora = new javax.swing.JLabel();
        txt_recurs_preuHora = new javax.swing.JTextField();
        lbl_recurs_preuDia = new javax.swing.JLabel();
        txt_recurs_preuDia = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        btn_recurs_Validar = new javax.swing.JButton();
        btn_recurs_Alta = new javax.swing.JButton();
        btn_recurs_Modificar = new javax.swing.JButton();
        btn_recurs_Eliminar = new javax.swing.JButton();
        btn_recurs_Cancelar = new javax.swing.JButton();

        lbl_recursos_titol.setFont(new java.awt.Font("Verdana", 0, 18)); // NOI18N
        lbl_recursos_titol.setText("Manteniment Recursos");

        lbl_recurs_codiRecurs.setText("Codi recurs");

        txt_recurs_codiRecurs.setToolTipText("");

        lbl_recurs_descripcio.setText("Descripció");

        lbl_recurs_existencies.setText("Existències");

        lbl_recurs_preuHora.setText("Preu hora");

        lbl_recurs_preuDia.setText("Preu dia");

        txt_recurs_preuDia.setToolTipText("");

        btn_recurs_Validar.setText("Validar");
        btn_recurs_Validar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_recurs_Validar_ActionPerformed(evt);
            }
        });

        btn_recurs_Alta.setText("Alta");
        btn_recurs_Alta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_recurs_Alta_ActionPerformed(evt);
            }
        });

        btn_recurs_Modificar.setText("Modificar");
        btn_recurs_Modificar.setToolTipText("");
        btn_recurs_Modificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_recurs_Modificar_ActionPerformed(evt);
            }
        });

        btn_recurs_Eliminar.setText("El·liminar");
        btn_recurs_Eliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_recurs_Eliminar_ActionPerformed(evt);
            }
        });

        btn_recurs_Cancelar.setText("Cancelar");
        btn_recurs_Cancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_recurs_Cancelar_ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lbl_recurs_existencies)
                        .addContainerGap(367, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lbl_recurs_preuHora)
                        .addContainerGap(373, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 399, Short.MAX_VALUE)
                            .addComponent(lbl_recursos_titol, javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btn_recurs_Alta, javax.swing.GroupLayout.DEFAULT_SIZE, 87, Short.MAX_VALUE)
                                .addGap(31, 31, 31)
                                .addComponent(btn_recurs_Modificar)
                                .addGap(30, 30, 30)
                                .addComponent(btn_recurs_Eliminar)
                                .addGap(26, 26, 26)
                                .addComponent(btn_recurs_Cancelar))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lbl_recurs_codiRecurs)
                                    .addComponent(lbl_recurs_descripcio))
                                .addGap(58, 58, 58)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(txt_recurs_codiRecurs, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(btn_recurs_Validar))
                                    .addComponent(txt_recurs_descripcio, javax.swing.GroupLayout.DEFAULT_SIZE, 287, Short.MAX_VALUE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                            .addComponent(txt_recurs_preuHora)
                                            .addComponent(txt_recurs_existencies, javax.swing.GroupLayout.DEFAULT_SIZE, 64, Short.MAX_VALUE))
                                        .addGap(92, 92, 92)
                                        .addComponent(lbl_recurs_preuDia)
                                        .addGap(30, 30, 30)
                                        .addComponent(txt_recurs_preuDia, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                        .addContainerGap(21, javax.swing.GroupLayout.PREFERRED_SIZE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lbl_recursos_titol)
                .addGap(41, 41, 41)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbl_recurs_codiRecurs)
                    .addComponent(btn_recurs_Validar)
                    .addComponent(txt_recurs_codiRecurs, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbl_recurs_descripcio)
                    .addComponent(txt_recurs_descripcio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbl_recurs_existencies)
                    .addComponent(txt_recurs_existencies, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbl_recurs_preuHora)
                    .addComponent(txt_recurs_preuHora, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbl_recurs_preuDia)
                    .addComponent(txt_recurs_preuDia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(29, 29, 29)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btn_recurs_Cancelar)
                    .addComponent(btn_recurs_Alta)
                    .addComponent(btn_recurs_Modificar)
                    .addComponent(btn_recurs_Eliminar))
                .addContainerGap(35, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

private void btn_recurs_Validar_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_recurs_Validar_ActionPerformed
// TODO add your handling code here:
    resource = null;
    try {
        if (comprovaCampValidInt(txt_recurs_codiRecurs.getText(), lbl_recurs_codiRecurs.getText())) {
        resource = resourceManager.getResource(txt_recurs_codiRecurs.getText());
        // Assigna els camps de l'aula trobada a les caixes
        activaBotonsNoAlta();
        carregaCampsPanel(resource);
        }
    } catch (RemoteException ex) {
    } catch(NullPointerException e){
        // Prepara camps per fer l'alta d'usuari.
        activaBotonsAlta();
        netejaCampsPanel();
    }

}//GEN-LAST:event_btn_recurs_Validar_ActionPerformed

private void btn_recurs_Alta_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_recurs_Alta_ActionPerformed
    try {
        // Amb els camps carregats al panel, es fa l'alta del recurs
        resource = new Resource();

        if (carregaResource(resource)) {
                resourceManager.addResource(resource);
                netejaCampsPanel();
                txt_recurs_codiRecurs.setText("");
                posicioInicialBotons();
        }
    } catch (RemoteException ex) {
        Logger.getLogger(AulaPanel.class.getName()).log(Level.SEVERE, null, ex);
    } catch(NullPointerException e) {
            Logger.getLogger(AulaPanel.class.getName()).log(Level.SEVERE, null, e);
    }
}//GEN-LAST:event_btn_recurs_Alta_ActionPerformed

private void btn_recurs_Modificar_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_recurs_Modificar_ActionPerformed
    resource = null;
    int optionType = JOptionPane.YES_NO_OPTION;
    int messageType = JOptionPane.INFORMATION_MESSAGE;

    try {
        // Amb el codi d'usuari, modifica el registre de la taula users
        resource = new Resource();

        if (carregaResource(resource)) {
            // Confirmació de la modificacio
            Integer sel = JOptionPane.showConfirmDialog(this,"Segur que vols fer la modificació en aquest resurs?","Manteniment recuros - Confirmació", optionType, messageType);
            if (sel != 1) {
            resourceManager.modifyResource(resource);
            }
            netejaCampsPanel();
            txt_recurs_codiRecurs.setText("");
            posicioInicialBotons();
        }

    } catch (RemoteException ex) {
        Logger.getLogger(AulaPanel.class.getName()).log(Level.SEVERE, null, ex);
    } catch(NullPointerException e) {}
}//GEN-LAST:event_btn_recurs_Modificar_ActionPerformed

private void btn_recurs_Eliminar_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_recurs_Eliminar_ActionPerformed
    int optionType = JOptionPane.YES_NO_OPTION;
    int messageType = JOptionPane.INFORMATION_MESSAGE;

    try {
        // Confirmació d'esborrat
        Integer sel = JOptionPane.showConfirmDialog(this,"Segur que vols eliminar aquest recurs?","Manteniment resursos - Confirmació", optionType, messageType);
        System.out.println("Dins btn_Recurs_Eliminar" + sel);
        if (sel != 1) {
            // Esborrat usuari
            String codiRecurs = txt_recurs_codiRecurs.getText();
            resourceManager.deleteResource(codiRecurs);
        }
        netejaCampsPanel();
        txt_recurs_codiRecurs.setText("");
        posicioInicialBotons();

    } catch (RemoteException ex) {
        Logger.getLogger(RecursPanel.class.getName()).log(Level.SEVERE, null, ex);
    } catch(NullPointerException e) {}
}//GEN-LAST:event_btn_recurs_Eliminar_ActionPerformed

private void btn_recurs_Cancelar_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_recurs_Cancelar_ActionPerformed
    netejaCampsPanel();
    txt_recurs_codiRecurs.setText("");
    posicioInicialBotons();
}//GEN-LAST:event_btn_recurs_Cancelar_ActionPerformed

    /**
     * Carrega el registre sobre els camps del panel per a ser mostrats. 
     * @autor Alex
     * @param aula
     * @return void
     */
    public void carregaCampsPanel(Resource resource) {
        txt_recurs_descripcio.setText(resource.getResource_desc());
        txt_recurs_preuHora.setText(String.valueOf(resource.getPrice_hour()));
        txt_recurs_preuDia.setText(String.valueOf(resource.getPrice_day()));
        txt_recurs_existencies.setText(String.valueOf(resource.getAmount()));
    }

   /**
     * Netaja els camps del panel. 
     * @autor Alex
     * @param 
     * @return void
     */
public void netejaCampsPanel() {
        txt_recurs_codiRecurs.setEnabled(true);
        txt_recurs_existencies.setText("0");
        txt_recurs_descripcio.setText("");
        txt_recurs_preuHora.setText("0");
        txt_recurs_preuDia.setText("0");
    }

/**
     * Activa el botons amb les accions a fer en la posició inicial.
     * @autor Alex
     * @return void
     */
    public void posicioInicialBotons(){
        btn_recurs_Alta.setEnabled(false);
        btn_recurs_Modificar.setEnabled(false);
        btn_recurs_Eliminar.setEnabled(false);
        btn_recurs_Cancelar.setEnabled(false);
    }
/**
     * Activa el botons amb les accions a fer en la posició "Alta aula".  
     * @autor Alex
     * @return void
     */
    public void activaBotonsAlta(){
        btn_recurs_Alta.setEnabled(true);
        btn_recurs_Modificar.setEnabled(false);
        btn_recurs_Eliminar.setEnabled(false);
        btn_recurs_Cancelar.setEnabled(true);

        txt_recurs_codiRecurs.setEnabled(true);
 }
/**
     * Activa el botons amb les accions a fer en la posició 
     * "Modificar aula" i "Eliminar aula".  
     * @autor Alex
     * @return void
     */
    public void activaBotonsNoAlta(){
        btn_recurs_Alta.setEnabled(false);
        btn_recurs_Modificar.setEnabled(true);
        btn_recurs_Eliminar.setEnabled(true);
        btn_recurs_Cancelar.setEnabled(true);

        txt_recurs_codiRecurs.setEnabled(false);
}
    /**
     * Comprova que el camp no sigui NULL
     * @autor Alex
     * @param camp a validar, nom camp a validar
     * @return true/false
     */
    public boolean comprovaCampValid(String camp, String titol) {
    int optionType = JOptionPane.DEFAULT_OPTION;
    int messageType = JOptionPane.ERROR_MESSAGE;

        if ( camp != null && !camp.equals("") ) {
            return true;
        } else {
            JOptionPane.showConfirmDialog(this,"Camp "+titol+" obligatori !","Manteniment recursos - Validació", optionType, messageType);
            return false;
        }
    }

    /**
     * Comprova que el camp sigui nummèric i que no sigui NULL
     * @autor Alex
     * @param camp a validar, nom camp a validar
     * @return true/false
     */
    public boolean comprovaCampValidInt(String camp, String titol) {
    int optionType = JOptionPane.DEFAULT_OPTION;
    int messageType = JOptionPane.ERROR_MESSAGE;

    // Comprova que sigui numèric
    try {
        Integer.parseInt(camp);
        return true;
    } catch (Exception e) {
        JOptionPane.showConfirmDialog(this,"Camp "+titol+" és obligatori i ha de ser numèric !","Manteniment recursos - Validació", optionType, messageType);
        return false;
    }
    
}

        /**
     * Comprova que el camp sigui nummèric i que no sigui NULL
     * @autor Alex
     * @param camp a validar, nom camp a validar
     * @return true/false
     */
    public boolean comprovaCampValidDouble(String camp, String titol) {
    int optionType = JOptionPane.DEFAULT_OPTION;
    int messageType = JOptionPane.ERROR_MESSAGE;

    // Comprova que sigui numèric
    try {
        Double.parseDouble(camp);
        return true;
    } catch (Exception e) {
        JOptionPane.showConfirmDialog(this,"Camp "+titol+" és obligatori i ha de ser numèric !","Manteniment aules - Validació", optionType, messageType);
        return false;
    }
    
}

    /**
     * Mètode que carrega els camps del registre i fa les validacions bàsiques.
     * @autor Alex
     * @param space
     * @return true/false
     */
    public boolean carregaResource(Resource resource) {
    boolean totOK = true;
    String varStr1 = "";
    String varStr2 = "";
    Date avui = new Date();

    /*
     * Codi recurs
     */    
    varStr1 = txt_recurs_codiRecurs.getText();
    varStr2 = lbl_recurs_codiRecurs.getText();
    if (comprovaCampValidInt(varStr1, varStr2)) resource.setResource_id(Integer.parseInt(varStr1));
    else totOK = false;

    /*
     * Descripció
     */    
    varStr1 = txt_recurs_descripcio.getText();
    varStr2 = lbl_recurs_descripcio.getText();
    if (comprovaCampValid(varStr1, varStr2)) resource.setResource_desc(varStr1);
    else totOK = false;

    /*
     * Capacitat
     */    
    varStr1 = txt_recurs_existencies.getText();
    varStr2 = lbl_recurs_existencies.getText();
    if (comprovaCampValidInt(varStr1, varStr2)) resource.setAmount(Integer.parseInt(varStr1));
    else totOK = false;

    /*
     * Preu hora
     */    
    varStr1 = txt_recurs_preuHora.getText();
    varStr2 = lbl_recurs_preuHora.getText();
    if (comprovaCampValidDouble(varStr1, varStr2)) resource.setPrice_hour(Double.parseDouble(varStr1));
    else totOK = false;

    /*
     * Preu dia
     */    
    varStr1 = txt_recurs_preuDia.getText();
    varStr2 = lbl_recurs_preuDia.getText();
    if (comprovaCampValidDouble(varStr1, varStr2)) resource.setPrice_day(Double.parseDouble(varStr1));
    else totOK = false;


    /*
     * Data creació
     */    
    resource.setCreationDate(avui);

    /*
     * Usuari creador
     */    
    resource.setCreationUser("");

    /*
     * Data recurs inactiva
     */    
    resource.setInactivationDate(avui);
    
    /*
     * Usuari recurs inactiva
     */    
    resource.setInactivationUser("");

    /*
     * Data registre
     */    
    resource.setRecordDate(avui);
    
    return totOK;
}


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_recurs_Alta;
    private javax.swing.JButton btn_recurs_Cancelar;
    private javax.swing.JButton btn_recurs_Eliminar;
    private javax.swing.JButton btn_recurs_Modificar;
    private javax.swing.JButton btn_recurs_Validar;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lbl_recurs_codiRecurs;
    private javax.swing.JLabel lbl_recurs_descripcio;
    private javax.swing.JLabel lbl_recurs_existencies;
    private javax.swing.JLabel lbl_recurs_preuDia;
    private javax.swing.JLabel lbl_recurs_preuHora;
    private javax.swing.JLabel lbl_recursos_titol;
    private javax.swing.JTextField txt_recurs_codiRecurs;
    private javax.swing.JTextField txt_recurs_descripcio;
    private javax.swing.JTextField txt_recurs_existencies;
    private javax.swing.JTextField txt_recurs_preuDia;
    private javax.swing.JTextField txt_recurs_preuHora;
    // End of variables declaration//GEN-END:variables

    @Override
    protected void setLabels() {
        // Etiquetes
        lbl_recursos_titol.setText(getText("lbl_recursos_titol")); 
        lbl_recurs_codiRecurs.setText(getText("lbl_recurs_codiRecurs")); 
        lbl_recurs_descripcio.setText(getText("lbl_recurs_descripcio")); 
        lbl_recurs_existencies.setText(getText("lbl_recurs_existencies")); 
        lbl_recurs_preuDia.setText(getText("lbl_recurs_preuDia")); 
        lbl_recurs_preuHora.setText(getText("lbl_recurs_preuHora")); 

        //Botons
        btn_recurs_Alta.setText(getText("btn_Aula_Alta")); 
        btn_recurs_Cancelar.setText(getText("btn_Aula_Cancelar")); 
        btn_recurs_Eliminar.setText(getText("btn_Aula_Eliminar")); 
        btn_recurs_Modificar.setText(getText("btn_Aula_Modificar")); 
        btn_recurs_Validar.setText(getText("btn_Aula_Validar")); 
    }
}
